#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytz

__author__ = 'lihaoquan'

def get_utc_from_local(dt, timezone):
    if timezone not in pytz.all_timezones:
        return dt

    # 验证客户端给出的时区是否有效
    tz = pytz.timezone(timezone)
    utc = pytz.utc.normalize(tz.localize(dt))
    return utc


def get_local_from_utc(dt, timezone):
    if timezone not in pytz.all_timezones:
        return dt

    # 验证客户端给出的时区是否有效
    tz = pytz.timezone(timezone)
    local = tz.normalize(pytz.utc.localize(dt))
    return local


def calculate_local_time(info, article):

    # 取得时区
    article['Timezone'] = article.get('Timezone')
    timezone = article.get('Timezone') or info.get('DefaultTimezone')
    if timezone is None:
        return

    # 重新计算时间
    tz = pytz.timezone(timezone)
    postOn = article['PostOn']
    article['PostOn'] = tz.normalize(pytz.utc.localize(postOn))

    # 时差
    article['TimezoneOffset'] = article.get('TimezoneOffset')

    # 是否出于夏令时
    article['IsDst'] = tz.dst(postOn).seconds != 0


def calculate_local_timeinfo(info, article):

    # 取得时区
    timezone = article.get('Timezone') or info.get('DefaultTimezone')
    if timezone is None:
        return

    article['Timezone'] = timezone

    # 重新计算时间
    tz = pytz.timezone(timezone)
    postOn = article['PostOn']
    article['PostOn'] = tz.normalize(pytz.utc.localize(postOn))

    # 时差
    offset = article.get('TimezoneOffset') or info.get('DefaultTimezoneOffset')
    article['TimezoneOffset'] = offset

    # 是否出于夏令时
    article['IsDst'] = tz.dst(postOn).seconds != 0

